<template>
  <div class="modifyAuth common-container">
    <div class="common-top">
      <span class="left">
        <span class="go-back" @click.stop="$router.go(-1)">返回</span>
      </span>
      <el-button type="primary" @click="save">保存</el-button>
    </div>
    <div class="common-bot">
      <div class="modify-bot bot-left">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item required label="权限名称" style="width:30%">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item required label="权限简述" style="width:50%">
            <el-input v-model="form.detail"></el-input>
          </el-form-item>
          <el-form-item label="排序值" style="width:30%">
            <el-input v-model="form.queue"></el-input>
            <!-- <span class="form-tip">排序值越大越靠前</span> -->
          </el-form-item>
          <el-form-item label="权限明细">
            <div class="auth-wrap">
              <ul class="out">
                <li v-for="item in tableData" :data-item-id="item.id" :key="item.id">
                  <div class="left-cont">
                    <el-checkbox v-model="item.checked" @change="check('parent',item)">{{item.name}}</el-checkbox>
                  </div>
                  <div class="center-cont">
                    <div
                      class="center-item"
                      v-for="firstChild in item.children"
                      :key="firstChild.id"
                    >
                      <div class="center-left">
                        <el-checkbox
                          v-model="firstChild.checked"
                          @change="check('firstChild',firstChild,item)"
                        >{{firstChild.name}}</el-checkbox>
                      </div>
                      <div class="center-right">
                        <div
                          class="right-item"
                          v-for="secondChild in firstChild.children"
                          :key="secondChild.id"
                        >
                          <el-checkbox
                            v-model="secondChild.checked"
                            @change="check('secondChild',secondChild,firstChild)"
                          >{{secondChild.name}}</el-checkbox>
                        </div>
                      </div>
                    </div>
                  </div>
                </li>
              </ul>
              <!-- <el-table
                :data="tableData"
                style="width: 100%;margin-bottom: 20px;"
                row-key="id"
                border
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              >
                <el-table-column prop="name" label="操作名" sortable width="180"></el-table-column>
                <el-table-column prop="address" label="是否启用">
                  <template slot-scope="scope">
                    <el-checkbox v-model="scope.row.checked" @change="changeChecked(scope.row)">
                      <i :style="scope.row.checked?'':'color:red'">{{scope.row.checked?"启用":"禁用"}}</i>
                    </el-checkbox>
                  </template>
                </el-table-column>
              </el-table>-->
            </div>
          </el-form-item>

          <el-form-item label="是否启用">
            <el-switch v-model="form.enable"></el-switch>
          </el-form-item>
        </el-form>
      </div>
      <div class="bot-right">
        <div class="top">
          <span class="tit">成员选择</span>
          <el-button type="primary" size="small" @click.stop="addUser">添加成员</el-button>
        </div>
        <div class="seled-user-list">
          <el-table :data="nowSelRoleUserArr" style="width: 100%">
            <el-table-column prop="name" label="姓名" width="180"></el-table-column>
            <el-table-column prop="mobile" label="电话"></el-table-column>
            <el-table-column label="性别">
              <template slot-scope="scope">
                <span>{{gender[scope.row.gender]}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <span class="span-modify del" @click.stop="remove(scope.row)">移除</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <el-dialog title="添加人员" :visible.sync="dialogVisible" width="50%">
      <div class="user-list">
        <el-table
          ref="multipleTable"
          :row-key="getRowKeys"
          :data="tableDataForUser"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="name" label="姓名" width="180"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column label="性别">
            <template slot-scope="scope">
              <span>{{gender[scope.row.gender]}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <span
                style="color:#409EFF;cursor:pointer;"
                @click.stop="addToNowRoleGroup(scope.row)"
              >添加</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureSelUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import ManaApi from "@/api/index";
export default {
  name: "ModifyAuth",
  data() {
    return {
      dialogVisible: false,
      gender: {
        female: "女",
        male: "男",
      },
      form: {
        formId: 0,
        parentId: 0,
        name: "",
        detail: "",
        enable: true,
        queue: 0,
        roles: [],
        userIds: [],
      },
      tableData: [],
      tableDataForUser: [],
      nowSelRoleUserArr: [],
      multipleSelection: [],
    };
  },
  methods: {
    sureSelUser() {
      this.nowSelRoleUserArr = this.multipleSelection;
      this.dialogVisible = false;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getRowKeys(row) {
      return row.id;
    },
    remove(item) {
      this.$confirm("确认此操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let nowSelRoleUserArr = this.nowSelRoleUserArr;
        let flagIndex;
        nowSelRoleUserArr.forEach((oitem, index) => {
          if (oitem.id == item.id) {
            flagIndex = index;
          }
        });
        nowSelRoleUserArr.splice(flagIndex, 1);
        this.nowSelRoleUserArr = nowSelRoleUserArr;
      });
    },
    addToNowRoleGroup(item) {
      this.$refs.multipleTable.toggleRowSelection(item, true);
      return;
      let nowSelRoleUserArr = this.nowSelRoleUserArr;
      let flag = true;
      for (let i = 0; i < nowSelRoleUserArr.length; i++) {
        if (nowSelRoleUserArr[i].id == item.id) {
          flag = false;
        }
      }
      if (flag) {
        nowSelRoleUserArr.push(item);
        this.$refs.multipleTable.toggleRowSelection(item, true);
      }
      this.nowSelRoleUserArr = nowSelRoleUserArr;
    },
    getUser(roleGroupId = 0) {
      return new Promise((resolve, reject) => {
        ManaApi.manager
          .list({
            limit: 100,
            page: 0,
            roleGroupId,
          })
          .then((res) => {
            resolve(res.data);
          });
      });
    },
    async addUser() {
      this.dialogVisible = true;
      let data = await this.getUser();
      this.tableDataForUser = data;
      let arr = [];
      data.forEach((item) => {
        for (let i = 0; i < this.nowSelRoleUserArr.length; i++) {
          if (item.id == this.nowSelRoleUserArr[i].id) {
            arr.push(item);
          }
        }
      });
      setTimeout(() => {
        arr.forEach((item) => {
          this.$refs.multipleTable.toggleRowSelection(item, true);
        });
      }, 100);
    },
    check(type, item, p = null) {
      let flag = false;
      switch (type) {
        case "parent":
          this.changeChecked(item);
          break;
        case "firstChild":
          // p.checked = item.checked;
          this.changeChecked(item);
          break;
        case "secondChild":
          for (let i = 0; i < p.children.length; i++) {
            if (p.children[i].checked) {
              flag = true;
            }
          }
          p.checked = flag;
          this.$nextTick(() => {
            this.rollBackChecked();
          });
          if (!flag) {
            this.changeChecked(item);
          }
          break;
        default:
          break;
      }
    },
    checkInfo() {
      if (String(this.form.name).trim() == "") {
        this.$message({
          type: "error",
          message: "请填写名称",
        });
        return false;
      }
      if (String(this.form.detail).trim() == "") {
        this.$message({
          type: "error",
          message: "请填写权限组简述",
        });
        return false;
      }
      if (this.form.roles.length == 0) {
        this.$message({
          type: "error",
          message: "请选择权限",
        });
        return false;
      }
      return true;
    },
    save() {
      let roles = [];
      let data = this.tableData;
      console.log(data);
      const format = (data) => {
        for (let i = 0; i < data.length; i++) {
          if (data[i].checked) {
            roles.push(data[i].id);
          }
          if (data[i].children) {
            format(data[i].children);
          }
        }
      };
      format(data);
      console.log(roles);
      let userIds = [];
      for (let i = 0; i < this.nowSelRoleUserArr.length; i++) {
        userIds.push(this.nowSelRoleUserArr[i].id);
      }
      this.$set(this.form, "roles", roles);
      this.$set(this.form, "userIds", userIds);
      if (!this.checkInfo()) {
        return;
      }
      ManaApi.authMana.modify(this.form).then((res) => {
        if (res.code == 200) {
          this.$message.success("操作成功");
          this.$router.go(-1);
        }
      });
    },
    // 初始换权限数组各参数
    formatAuth(data, pid = 0) {
      if (data) {
        for (let i = 0; i < data.length; i++) {
          data[i].checked = false;
          data[i].pid = pid;
          if (data[i].children) {
            this.formatAuth(data[i].children, data[i].id);
          }
        }
      }
      return data;
    },
    getAllAuth() {
      return new Promise((resolve, reject) => {
        ManaApi.authMana.allRoles({}).then((res) => {
          resolve(res.data);
        });
      });
    },
    changeChecked(item) {
      // 树形级联操作
      let isChecked = item.checked;
      const format = (item) => {
        if (item.children) {
          let trueArr = [];
          for (let i = 0; i < item.children.length; i++) {
            if (item.children[i].checked) {
            }
            item.children[i].checked = isChecked;
            if (item.children[i].children) {
              for (let j = 0; j < item.children[i].children.length; j++) {
                format(item.children[i].children[j]);
              }
            }
          }
        } else {
          item.checked = isChecked;
        }
      };
      format(item);
      this.$nextTick(() => {
        this.rollBackChecked();
      });
      // this.rollChecked();
    },
    rollBackChecked() {
      let that = this;
      $(".auth-wrap li").each(function () {
        let itemId = $(this).data("item-id");
        if ($(this).find(".center-cont .el-checkbox.is-checked").length) {
          console.log(itemId);
          that.tableData.forEach((item) => {
            if (item.id == itemId) {
              item.checked = true;
              item.isChecked = true;
            }
          });
        } else {
          that.tableData.forEach((item) => {
            if (item.id == itemId) {
              item.checked = false;
              item.isChecked = false;
            }
          });
        }
      });
    },
    rollChecked() {
      let data = this.tableData;
      const format = (item, p = null) => {
        console.log(item);
        for (let i = 0; i < item.length; i++) {
          let flag = false;
          let trueArr = [];
          if (item[i].children) {
            for (let j = 0; j < item[i].children.length; j++) {
              if (item[i].children[j].checked) {
                trueArr.push(item[i].children[j]);
              }
              if (item[i].children[j].children) {
                console.log(item[i].children[j].children);
                format(item[i].children[j].children, item[i].children[j]);
              }
            }
            item[i].checked = trueArr.length > 0 ? true : false;
            trueArr = [];
          } else {
            if (item[i].checked) {
              trueArr.push(item[i]);
            }
            p.checked = trueArr.length > 0 ? true : false;
            trueArr = [];
          }
        }
      };
      format(data);
    },
    async getInfo() {
      let userData = await this.getUser(this.$route.query.id);
      this.nowSelRoleUserArr = userData;
      ManaApi.authMana
        .detail({
          targetId: this.$route.query.id,
        })
        .then((res) => {
          let data = JSON.parse(JSON.stringify(this.tableData));
          let roles = res.data.roles;
          console.log(roles);
          const format = (data) => {
            for (let i = 0; i < data.length; i++) {
              if (roles.indexOf(data[i].id) != -1) {
                data[i].checked = true;
              }
              if (data[i].children) {
                format(data[i].children);
              }
            }
          };
          format(data);
          console.log(data);
          this.tableData = data;
          let userIds = [];
          for (let i = 0; i < userData.length; i++) {
            userIds.push(userData[i].id);
          }
          this.form = {
            formId: res.data.id,
            parentId: res.data.parentId,
            name: res.data.name,
            detail: res.data.detail,
            enable: res.data.enable,
            queue: res.data.queue,
            roles: res.data.roles,
            userIds,
          };
        });
    },
  },
  async mounted() {
    let data = await this.getAllAuth();
    this.tableData = this.formatAuth(data);
    if (this.$route.query.type == "edit") {
      this.getInfo();
    }
  },
};
</script>
<style scoped lang="scss">
.modifyAuth {
  .modify-bot {
    width: 50%;
    padding: 30px 10px;
    padding-right: 50px;
    border-right: 1px solid #ddd;
    .auth-wrap {
      font-size: 0;
      ul.out {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        font-size: 14px;
        li {
          display: flex;
          justify-content: center;
          align-items: top;
          width: 100%;
          border: 1px solid #ddd;
          border-bottom: none;
          .el-checkbox {
            margin-right: 10px;
          }
          &:last-child {
            border-bottom: 1px solid #ddd;
          }
          .left-cont {
            flex: 1;
            text-align: left;
            padding-left: 10px;
          }
          .center-cont {
            flex: 4;
            .center-item {
              border: 1px solid #ddd;
              border-bottom: none;
              text-align: left;
              display: flex;
              border-right: none;
              &:first-child {
                border-top: none;
              }
              .center-left {
                flex: 1;
                border-right: 1px solid #ddd;
                padding-left: 10px;
              }
              .center-right {
                flex: 3;
                display: flex;
                flex-wrap: wrap;
                padding-left: 10px;
              }
            }
          }
        }
      }
    }
  }
  .bot-right {
    .top {
      font-size: 12px;
      color: red;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
    }
    .seled-user-list {
      width: 90%;
    }
  }
}
</style>